package com.lin.manager.secure.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lin.manager.secure.ex.CustomAccessDeniedException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @作者: 林江
 * @创建时间: 2024/3/15
 * @功能:
 */
public class CustomSecurityExceptionHandler implements AccessDeniedHandler, AuthenticationEntryPoint {
    ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 认证异常
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException auth) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.FORBIDDEN.value());
        map.put("msg", "认证失败");
        map.put("data", auth.getMessage());

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(map));

    }

    /**
     * 权限异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exception) throws IOException, ServletException {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        if (exception instanceof CustomAccessDeniedException) {
            map.put("msg", exception.getMessage());
        } else {
            map.put("msg", "无权访问");
            map.put("data", exception.getMessage());
        }

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(map));

    }
}
